package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.wx.api.WxMaApi;
import net.guerlab.smart.wx.api.feign.FeignWxMaApi;
import net.guerlab.smart.wx.core.domain.LoginResponse;
import net.guerlab.smart.wx.core.domain.MaEncryptedData;
import net.guerlab.web.result.Result;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(WxMaApiLocalServiceAutoConfigure.class)
public class WxMaApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(WxMaApi.class)
    public WxMaApi wxMaApiFeignWrapper(FeignWxMaApi api) {
        return new WxMaApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class WxMaApiFeignWrapper implements WxMaApi {

        private FeignWxMaApi api;

        @Override
        public LoginResponse login(String appId, String code) {
            Result<LoginResponse> result = api.login(appId, code);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }

        @Override
        public LoginResponse register(String appId, String openId, MaEncryptedData encryptedData) {
            Result<LoginResponse> result = api.register(appId, openId, encryptedData);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }

        @Override
        public String getAccessToken(String appId) {
            Result<String> result = api.getAccessToken(appId);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }
    }

}
